const Service = require("egg").Service;
const NotFoundException = require("../exception/not_found");

Date.prototype.Format = function (fmt) {
  const o = {
    "M+": this.getMonth() + 1, // 月份
    "d+": this.getDate(), // 日
    "H+": this.getHours(), // 小时
    "m+": this.getMinutes(), // 分
    "s+": this.getSeconds(), // 秒
    "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
    S: this.getMilliseconds(), // 毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (const k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return fmt;
};

class ClassesService extends Service {
  async queryClassListByName(params) {
    const { ctx, app } = this;
    const { class_name } = params;
    const classList = await ctx.model.Class.findOne({
      where: {
        class_name: class_name,
      },
      include: {
        as: "teacher",
        model: app.model.User,
        include: {
          as: "role",
          model: app.model.Role,
          where: {
            role_id: 3 // 教师角色
          }
        },
      },
    });
    if (classList === null) {
      // 抛出异常
      throw new NotFoundException("查询失败", 500);
    }
    return classList;
  }

  async queryClassList(params) {
    const { ctx } = this;
    const { pageSize, current, class_name } = params;
    const currentPage = parseInt(current) || 1;
    const currentPageSize = parseInt(pageSize) || 10;
    const classList = await ctx.model.Class.queryClassList(
      currentPageSize,
      currentPage,
      class_name
    );
    if (classList === null) {
      // 抛出异常
      throw new NotFoundException("查询失败", 500);
    }
    return classList;
  }

  async createClass(params) {
    const { ctx } = this;
    try {
      const result = await ctx.model.transaction(async (t) => {
        const { class_name, description } = params;
        const classItem = await ctx.model.Class.create(
          {
            class_name,
            description,
            is_super: 0,
          },
          { transaction: t }
        );
        return classItem;
      });
      return result;
    } catch (error) {
      console.log('新增失败', error);
      throw new NotFoundException("新增失败", 500);
    }
  }

  async updateClassInfo(id, class_name, description) {
    const { ctx } = this;
    try {
      const result = await ctx.model.transaction(async (t) => {
        const classItem = await ctx.model.Class.findOne(
          {
            where: {
              class_id: id,
            },
          },
          { transaction: t }
        );
        const updated_at = new Date().Format("yyyy-MM-dd HH:mm:ss");
        await classItem.update(
          {
            class_name,
            description,
            updated_at,
          },
          { transaction: t }
        );
      });
      return result;
    } catch (error) {
      throw new NotFoundException("编辑失败", 500);
    }
  }

  async destroy(id) {
    const { ctx } = this;
    try {
      const result = await ctx.model.transaction(async (t) => {
        const classItem = await ctx.model.Class.destroy(
          { where: { class_id: id } },
          { transaction: t }
        );
        await ctx.model.UserClass.destroy(
          { where: { class_id: id } },
          { transaction: t }
        );
        return classItem;
      });
      return result;
    } catch (error) {
      throw new NotFoundException("删除失败", 500);
    }
  }
}

module.exports = ClassesService;
